<script lang="ts" setup>
import { inject, nextTick, ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';
import { cloneDeep } from '@vben/utils';

import {
  ElButton,
  ElDialog,
  ElDivider,
  ElDrawer,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessageBox,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import ProcessListenerDialog from '#/components/bpmn-process-designer/package/penal/listeners/ProcessListenerDialog.vue';

import { createListenerObject, updateElementExtensions } from '../../utils';
import {
  eventType,
  fieldType,
  initListenerForm,
  initListenerForm2,
  initListenerType,
  listenerType,
} from './utilSelf';

defineOptions({ name: 'UserTaskListeners' });

const props = defineProps<Props>();

interface Props {
  id?: string;
  type?: string;
}

const prefix = inject<string>('prefix');
const width = inject<number>('width');
const elementListenersList = ref<any[]>([]);
const listenerEventTypeObject = ref(eventType);
const listenerTypeObject = ref(listenerType);
const listenerFormModelVisible = ref(false);
const listenerForm = ref<any>({});
const fieldTypeObject = ref(fieldType);
const fieldsListOfListener = ref<any[]>([]);
const listenerFieldFormModelVisible = ref(false); // 监听器 注入字段表单弹窗 显示状态
const editingListenerIndex = ref(-1); // 监听器所在下标，-1 为新增
const editingListenerFieldIndex = ref<any>(-1); // 字段所在下标，-1 为新增
const listenerFieldForm = ref<any>({}); // 监听器 注入字段 详情表单
const bpmnElement = ref<any>();
const bpmnElementListeners = ref<any[]>([]);
const otherExtensionList = ref<any[]>([]);
const listenerFormRef = ref<any>({});
const listenerFieldFormRef = ref<any>({});

interface BpmnInstances {
  bpmnElement: any;
  [key: string]: any;
}

declare global {
  interface Window {
    bpmnInstances?: BpmnInstances;
  }
}

const bpmnInstances = () => window.bpmnInstances;

const resetListenersList = () => {
  // console.log(
  //   bpmnInstances().bpmnElement,
  //   'window.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElement',
  // );
  bpmnElement.value = bpmnInstances()?.bpmnElement;
  otherExtensionList.value = [];
  bpmnElementListeners.value =
    bpmnElement.value.businessObject?.extensionElements?.values.filter(
      (ex: any) => ex.$type === `${prefix}:TaskListener`,
    ) ?? [];
  elementListenersList.value = bpmnElementListeners.value.map((listener) =>
    initListenerType(listener),
  );
};
const openListenerForm = (listener: any, index?: number) => {
  if (listener) {
    listenerForm.value = initListenerForm(listener);
    editingListenerIndex.value = index || -1;
  } else {
    listenerForm.value = {};
    editingListenerIndex.value = -1; // 标记为新增
  }
  if (listener && listener.fields) {
    fieldsListOfListener.value = listener.fields.map((field: any) => ({
      ...field,
      fieldType: field.string ? 'string' : 'expression',
    }));
  } else {
    fieldsListOfListener.value = [];
    listenerForm.value.fields = [];
  }
  // 打开侧边栏并清楚验证状态
  listenerFormModelVisible.value = true;
  nextTick(() => {
    if (listenerFormRef.value) listenerFormRef.value.clearValidate();
  });
};
// 移除监听器
const removeListener = (_: any, index: number) => {
  // console.log(listener, 'listener');
  ElMessageBox.confirm('确认移除该监听器吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      bpmnElementListeners.value.splice(index, 1);
      elementListenersList.value.splice(index, 1);
      updateElementExtensions(bpmnElement.value, [
        ...otherExtensionList.value,
        ...bpmnElementListeners.value,
      ]);
    })
    .catch(() => {
      // console.info('操作取消');
    });
};
// 保存监听器
const saveListenerConfig = async () => {
  const validateStatus = await listenerFormRef.value.validate();
  if (!validateStatus) return; // 验证不通过直接返回
  const listenerObject = createListenerObject(listenerForm.value, true, prefix);
  if (editingListenerIndex.value === -1) {
    bpmnElementListeners.value.push(listenerObject);
    elementListenersList.value.push(listenerForm.value);
  } else {
    bpmnElementListeners.value.splice(
      editingListenerIndex.value,
      1,
      listenerObject,
    );
    elementListenersList.value.splice(
      editingListenerIndex.value,
      1,
      listenerForm.value,
    );
  }
  // 保存其他配置
  otherExtensionList.value =
    bpmnElement.value.businessObject?.extensionElements?.values?.filter(
      (ex: any) => ex.$type !== `${prefix}:TaskListener`,
    ) ?? [];
  updateElementExtensions(bpmnElement.value, [
    ...otherExtensionList.value,
    ...bpmnElementListeners.value,
  ]);
  // 4. 隐藏侧边栏
  listenerFormModelVisible.value = false;
  listenerForm.value = {};
};

// 打开监听器字段编辑弹窗
const openListenerFieldForm = (field: any, index?: number) => {
  listenerFieldForm.value = field ? cloneDeep(field) : {};
  editingListenerFieldIndex.value = field ? index : -1;
  listenerFieldFormModelVisible.value = true;
  nextTick(() => {
    if (listenerFieldFormRef.value) listenerFieldFormRef.value.clearValidate();
  });
};
// 保存监听器注入字段
const saveListenerFiled = async () => {
  const validateStatus = await listenerFieldFormRef.value.validate();
  if (!validateStatus) return; // 验证不通过直接返回
  if (editingListenerFieldIndex.value === -1) {
    fieldsListOfListener.value.push(listenerFieldForm.value);
    listenerForm.value.fields.push(listenerFieldForm.value);
  } else {
    fieldsListOfListener.value.splice(
      editingListenerFieldIndex.value,
      1,
      listenerFieldForm.value,
    );
    listenerForm.value.fields.splice(
      editingListenerFieldIndex.value,
      1,
      listenerFieldForm.value,
    );
  }
  listenerFieldFormModelVisible.value = false;
  nextTick(() => {
    listenerFieldForm.value = {};
  });
};
// 移除监听器字段
const removeListenerField = (_: any, index: number) => {
  // console.log(field, 'field');
  ElMessageBox.confirm('确认移除该字段吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      fieldsListOfListener.value.splice(index, 1);
      listenerForm.value.fields.splice(index, 1);
    })
    .catch(() => {
      // console.info('操作取消');
    });
};

// 打开监听器弹窗
const processListenerDialogRef = ref<any>();
const openProcessListenerDialog = async () => {
  processListenerDialogRef.value.open('task');
};
const selectProcessListener = (listener: any) => {
  const listenerForm = initListenerForm2(listener);
  const listenerObject = createListenerObject(listenerForm, true, prefix);
  bpmnElementListeners.value.push(listenerObject);
  elementListenersList.value.push(listenerForm);

  // 保存其他配置
  otherExtensionList.value =
    bpmnElement.value.businessObject?.extensionElements?.values?.filter(
      (ex: any) => ex.$type !== `${prefix}:TaskListener`,
    ) ?? [];
  updateElementExtensions(
    bpmnElement.value,
    otherExtensionList.value?.concat(bpmnElementListeners.value),
  );
};

watch(
  () => props.id,
  (val) => {
    val &&
      val.length > 0 &&
      nextTick(() => {
        resetListenersList();
      });
  },
  { immediate: true },
);
</script>
<template>
  <div class="panel-tab__content">
    <ElTable :data="elementListenersList" size="small" border>
      <ElTableColumn type="index" label="序号" width="50" />
      <ElTableColumn
        prop="event"
        label="事件类型"
        width="80"
        show-overflow-tooltip
        :formatter="
          (row: any) =>
            listenerEventTypeObject[row.event as keyof typeof eventType]
        "
      />
      <ElTableColumn
        prop="id"
        label="事件id"
        width="80"
        show-overflow-tooltip
      />
      <ElTableColumn
        prop="listenerType"
        label="监听器类型"
        width="80"
        show-overflow-tooltip
        :formatter="
          (row: any) =>
            listenerTypeObject[row.listenerType as keyof typeof listenerType]
        "
      />
      <ElTableColumn label="操作" width="90" fixed="right">
        <template #default="{ row, $index }">
          <ElButton
            size="small"
            type="primary"
            link
            @click="openListenerForm(row, $index)"
          >
            编辑
          </ElButton>
          <ElDivider direction="vertical" />
          <ElButton
            size="small"
            type="danger"
            link
            @click="removeListener(row, $index)"
          >
            移除
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>
    <div class="element-drawer__button">
      <ElButton size="small" type="primary" @click="openListenerForm(null)">
        <template #icon> <IconifyIcon icon="ep:plus" /></template>
        添加监听器
      </ElButton>
      <ElButton size="small" @click="openProcessListenerDialog">
        <template #icon> <IconifyIcon icon="ep:select" /></template>
        选择监听器
      </ElButton>
    </div>

    <!-- 监听器 编辑/创建 部分 -->
    <ElDrawer
      v-model="listenerFormModelVisible"
      title="任务监听器"
      :size="width"
      destroy-on-close
    >
      <ElForm :model="listenerForm" ref="listenerFormRef">
        <ElFormItem
          label="事件类型"
          prop="event"
          :rules="[{ required: true, message: '请选择事件类型' }]"
        >
          <ElSelect v-model="listenerForm.event">
            <ElOption
              v-for="key in Object.keys(listenerEventTypeObject)"
              :key="key"
              :label="listenerEventTypeObject[key as keyof typeof eventType]"
              :value="key"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem
          label="监听器ID"
          prop="id"
          :rules="[{ required: true, message: '请输入监听器ID' }]"
        >
          <ElInput v-model="listenerForm.id" clearable />
        </ElFormItem>
        <ElFormItem
          label="监听器类型"
          prop="listenerType"
          :rules="[{ required: true, message: '请选择监听器类型' }]"
        >
          <ElSelect v-model="listenerForm.listenerType">
            <ElOption
              v-for="key in Object.keys(listenerTypeObject)"
              :key="key"
              :label="listenerTypeObject[key as keyof typeof listenerType]"
              :value="key"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem
          v-if="listenerForm.listenerType === 'classListener'"
          label="Java类"
          prop="class"
          key="listener-class"
          :rules="[{ required: true, message: '请输入Java类' }]"
        >
          <ElInput v-model="listenerForm.class" clearable />
        </ElFormItem>
        <ElFormItem
          v-if="listenerForm.listenerType === 'expressionListener'"
          label="表达式"
          prop="expression"
          key="listener-expression"
          :rules="[{ required: true, message: '请输入表达式' }]"
        >
          <ElInput v-model="listenerForm.expression" clearable />
        </ElFormItem>
        <ElFormItem
          v-if="listenerForm.listenerType === 'delegateExpressionListener'"
          label="代理表达式"
          prop="delegateExpression"
          key="listener-delegate"
          :rules="[{ required: true, message: '请输入代理表达式' }]"
        >
          <ElInput v-model="listenerForm.delegateExpression" clearable />
        </ElFormItem>
        <template v-if="listenerForm.listenerType === 'scriptListener'">
          <ElFormItem
            label="脚本格式"
            prop="scriptFormat"
            key="listener-script-format"
            :rules="[{ required: true, message: '请填写脚本格式' }]"
          >
            <ElInput v-model="listenerForm.scriptFormat" clearable />
          </ElFormItem>
          <ElFormItem
            label="脚本类型"
            prop="scriptType"
            key="listener-script-type"
            :rules="[{ required: true, message: '请选择脚本类型' }]"
          >
            <ElSelect v-model="listenerForm.scriptType">
              <ElOption label="内联脚本" value="inlineScript" />
              <ElOption label="外部脚本" value="externalScript" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            v-if="listenerForm.scriptType === 'inlineScript'"
            label="脚本内容"
            prop="value"
            key="listener-script"
            :rules="[{ required: true, message: '请填写脚本内容' }]"
          >
            <ElInput v-model="listenerForm.value" clearable />
          </ElFormItem>
          <ElFormItem
            v-if="listenerForm.scriptType === 'externalScript'"
            label="资源地址"
            prop="resource"
            key="listener-resource"
            :rules="[{ required: true, message: '请填写资源地址' }]"
          >
            <ElInput v-model="listenerForm.resource" clearable />
          </ElFormItem>
        </template>

        <template v-if="listenerForm.event === 'timeout'">
          <ElFormItem
            label="定时器类型"
            prop="eventDefinitionType"
            key="eventDefinitionType"
          >
            <ElSelect v-model="listenerForm.eventDefinitionType">
              <ElOption label="日期" value="date" />
              <ElOption label="持续时长" value="duration" />
              <ElOption label="循环" value="cycle" />
              <ElOption label="无" value="null" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            v-if="
              !!listenerForm.eventDefinitionType &&
              listenerForm.eventDefinitionType !== 'null'
            "
            label="定时器"
            prop="eventTimeDefinitions"
            key="eventTimeDefinitions"
            :rules="[{ required: true, message: '请填写定时器配置' }]"
          >
            <ElInput v-model="listenerForm.eventTimeDefinitions" clearable />
          </ElFormItem>
        </template>
      </ElForm>

      <ElDivider />
      <div class="mb-2 flex justify-between">
        <span class="flex items-center">
          <IconifyIcon icon="ep:menu" class="mr-2 text-gray-600" />
          注入字段
        </span>
        <ElButton
          type="primary"
          title="添加字段"
          @click="openListenerFieldForm(null)"
        >
          <template #icon>
            <IconifyIcon icon="ep:plus" />
          </template>
          添加字段
        </ElButton>
      </div>
      <ElTable
        :data="fieldsListOfListener"
        size="small"
        :max-height="240"
        border
        style="flex: none"
      >
        <ElTableColumn type="index" label="序号" width="50" />
        <ElTableColumn prop="name" label="字段名称" width="100" />
        <ElTableColumn
          prop="fieldType"
          label="字段类型"
          width="80"
          show-overflow-tooltip
          :formatter="
            (row: any) =>
              fieldTypeObject[row.fieldType as keyof typeof fieldType]
          "
        />
        <ElTableColumn
          label="字段值/表达式"
          width="100"
          show-overflow-tooltip
          :formatter="(row: any) => row.string || row.expression"
        />
        <ElTableColumn label="操作" width="100" fixed="right">
          <template #default="{ row, $index }">
            <ElButton
              size="small"
              type="primary"
              link
              @click="openListenerFieldForm(row, $index)"
            >
              编辑
            </ElButton>
            <ElDivider direction="vertical" />
            <ElButton
              size="small"
              type="danger"
              link
              @click="removeListenerField(row, $index)"
            >
              移除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>

      <div class="element-drawer__button">
        <ElButton size="small" @click="listenerFormModelVisible = false">
          取 消
        </ElButton>
        <ElButton size="small" type="primary" @click="saveListenerConfig">
          保 存
        </ElButton>
      </div>
    </ElDrawer>

    <!-- 注入字段 编辑/创建 部分 -->
    <ElDialog
      title="字段配置"
      v-model="listenerFieldFormModelVisible"
      width="600px"
      destroy-on-close
    >
      <ElForm :model="listenerFieldForm" ref="listenerFieldFormRef">
        <ElFormItem
          label="字段名称："
          prop="name"
          :rules="[{ required: true, message: '请输入字段名称' }]"
        >
          <ElInput v-model="listenerFieldForm.name" clearable />
        </ElFormItem>
        <ElFormItem
          label="字段类型："
          prop="fieldType"
          :rules="[{ required: true, message: '请选择字段类型' }]"
        >
          <ElSelect v-model="listenerFieldForm.fieldType">
            <ElOption
              v-for="key in Object.keys(fieldTypeObject)"
              :key="key"
              :label="fieldTypeObject[key as keyof typeof fieldType]"
              :value="key"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem
          v-if="listenerFieldForm.fieldType === 'string'"
          label="字段值："
          prop="string"
          key="field-string"
          :rules="[{ required: true, message: '请输入字段值' }]"
        >
          <ElInput v-model="listenerFieldForm.string" clearable />
        </ElFormItem>
        <ElFormItem
          v-if="listenerFieldForm.fieldType === 'expression'"
          label="表达式："
          prop="expression"
          key="field-expression"
          :rules="[{ required: true, message: '请输入表达式' }]"
        >
          <ElInput v-model="listenerFieldForm.expression" clearable />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton size="small" @click="listenerFieldFormModelVisible = false">
          取 消
        </ElButton>
        <ElButton size="small" type="primary" @click="saveListenerFiled">
          确 定
        </ElButton>
      </template>
    </ElDialog>
  </div>

  <!-- 选择弹窗 -->
  <ProcessListenerDialog
    ref="processListenerDialogRef"
    @select="selectProcessListener"
  />
</template>
